package com.sena.engine.snmp.utils;

import com.sena.engine.common.enums.ResultCodeEnum;
import com.sena.engine.common.exception.SenaSnmpRunTimeException;
import com.sena.engine.enums.SnmpResultCodeEnum;
import com.sena.engine.snmp.base.SnmpMappingInfo;
import com.sena.engine.snmp.mib.MibLoaderBuilder;
import net.percederberg.mibble.MibLoader;
import net.percederberg.mibble.MibType;
import net.percederberg.mibble.MibValueSymbol;
import net.percederberg.mibble.snmp.SnmpIndex;
import net.percederberg.mibble.snmp.SnmpObjectType;
import net.percederberg.mibble.value.ObjectIdentifierValue;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.snmp4j.PDU;
import org.snmp4j.PDUv1;
import org.snmp4j.ScopedPDU;
import org.snmp4j.Snmp;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.*;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

/**
 * snmp工具类
 */
public class SnmpUtils {

    private static final Logger log = LoggerFactory.getLogger(SnmpUtils.class);

    /**
     * 获取 oid值
     *
     * @param clazz
     * @return
     * @throws SenaSnmpRunTimeException
     */
    public static String getMibOIDofClass(Class clazz) throws SenaSnmpRunTimeException {
        try {
            Object obj = clazz.newInstance();
            return ((SnmpMappingInfo) obj).getMappingOID();
        } catch (Exception e) {
            log.error("获取:{} 对应的oid时出错:{}", clazz.getName(), e.getMessage());
            throw new SenaSnmpRunTimeException(SnmpResultCodeEnum.SERVER_NODE_NOT_FOUND, "获取" + clazz + "对应的oid时出错");
        }
    }

    /**
     * 设置值
     *
     * @param object
     * @param filedName
     * @param variable
     */
    public static void setFieldValue(Object object, String filedName, Variable variable) {
        try {
            String methodName = "set" + filedName.replaceFirst(filedName.substring(0, 1), filedName.substring(0, 1).toUpperCase());
            Class clazz = object.getClass();
            Field field = clazz.getDeclaredField(filedName);
            if (field == null) {
                return;
            }
            Class fieldType = field.getType();
            Method method = clazz.getMethod(methodName, fieldType);
            String typeName = fieldType.getName();
            if (typeName.equalsIgnoreCase("int")) {
                int value = variable.toInt();
                if (variable instanceof Null) {
                    value = 0;
                }
                method.invoke(object, new Integer(value));
            } else if (typeName.equalsIgnoreCase("long")) {
                long value = variable.toLong();
                if (variable instanceof Null) {
                    value = 0L;
                }
                method.invoke(object, new Long(value));
            } else if ("java.lang.String".equalsIgnoreCase(typeName)) {
                method.invoke(object, variable.toString());
            }
        } catch (Exception e) {
            log.error("给对象[" + object.getClass() + "]的属性[" + filedName + "]赋值失败:" + e.getMessage());
            log.debug(e.getMessage());
        }

    }

    /**
     * 获取值
     *
     * @param var0
     * @param var1
     * @param var2
     * @return
     */
    public static Variable getFieldValue(Object var0, String var1, MibType var2) {
        try {
            String var3 = "get" + var1.replaceFirst(var1.substring(0, 1), var1.substring(0, 1).toUpperCase());
            Class var4 = var0.getClass();
            Field var5 = var4.getDeclaredField(var1);
            if (var5 == null) {
                return null;
            } else {
                Method var6 = var4.getMethod(var3);
                Object var7 = var6.invoke(var0);
                return getVariable(var2, var7);
            }
        } catch (Exception var8) {
            log.error("给对象[" + var0.getClass() + "]的属性[" + var1 + "]赋值失败:" + var8.getMessage());

            return null;
        }
    }

    public static Variable getVariable(MibType mibType, Object obj) {
        if (mibType.hasTag(0, 2)) {
            Integer32 value = new Integer32();
            value.setValue(obj.toString());
            return value;
        } else if (mibType.hasTag(1, 1)) {
            Counter32 value = new Counter32();
            value.setValue("" + obj);
            return value;
        } else if (mibType.hasTag(1, 2)) {
            Gauge32 value = new Gauge32();
            value.setValue("" + obj);
            return value;
        } else if (mibType.hasTag(0, 4)) {
            OctetString value = new OctetString();
            try {
                byte[] bytes = ("" + obj).getBytes(StandardCharsets.UTF_8);
                value = new OctetString(bytes);
            } catch (Exception var4) {
            }
            return value;
        } else if (mibType.hasTag(0, 6)) {
            OID value = new OID("" + obj);
            return value;
        } else if (mibType.hasTag(1, 0)) {
            IpAddress value = new IpAddress("" + obj);
            return value;
        } else if (mibType.hasTag(1, 3)) {
            TimeTicks value = new TimeTicks();
            value.setValue("" + obj);
            return value;
        } else if (mibType.hasTag(1, 4)) {
            Opaque value = new Opaque(("" + obj).getBytes());
            return value;
        } else if (mibType.hasTag(1, 6)) {
            Counter64 value = new Counter64();
            value.setValue("" + obj);
            return value;
        } else {
            log.error("不支持的snmp mib数据类型:{}", mibType);
            return new Null();
        }
    }

    public static String getTableOrGroupIndexOID(Object obj, MibValueSymbol mibValueSymbol) throws SenaSnmpRunTimeException {
        if (mibValueSymbol.isTableRow()) {
            String mappingOID;
            if (obj instanceof SnmpMappingInfo) {
                mappingOID = ((SnmpMappingInfo) obj).getTableIndexOID();
                if (StringUtils.isNoneEmpty(mappingOID)) {
                    return mappingOID;
                }
            } else {
                mappingOID = "";
                ArrayList list = ((SnmpObjectType) mibValueSymbol.getType()).getIndex();

                for (int var4 = 0; var4 < list.size(); ++var4) {
                    SnmpIndex snmpIndex = (SnmpIndex) list.get(var4);
                    ObjectIdentifierValue objectIdentifierValue = (ObjectIdentifierValue) snmpIndex.getValue();
                    String name = objectIdentifierValue.getName();
                    mappingOID = mappingOID + getFieldValue(obj, name, ((SnmpObjectType) objectIdentifierValue.getSymbol().getType()).getSyntax());
                }
            }
            return mappingOID;
        } else {
            return "0";
        }

    }



    /**
     * 获取对象字段在mib节点
     *
     * @param clazz
     * @param mibValueSymbol
     * @return
     */
    public static List<MibValueSymbol> getFieldsInMibNode(Class clazz, MibValueSymbol mibValueSymbol) {
        Field[] fields = clazz.getDeclaredFields();
        List<MibValueSymbol> symbolList = new ArrayList<>();
        for (int i = 0; i < fields.length; i++) {
            String fieldName = fields[i].getName();
            MibValueSymbol[] mibValueSymbols = mibValueSymbol.getChildren();
            for (int j = 0; j < mibValueSymbols.length; j++) {
                if (mibValueSymbols[j].getName().equals(fieldName)) {
                    symbolList.add(mibValueSymbols[j]);
                    break;
                }
            }
        }
        return symbolList;
    }

    public static Vector getWritedFieldsInMibNode(Class var0, MibValueSymbol var1) {
        Field[] var2 = var0.getDeclaredFields();
        Vector var3 = new Vector();

        for (int var4 = 0; var4 < var2.length; ++var4) {
            String var5 = var2[var4].getName();
            MibValueSymbol[] var6 = var1.getChildren();

            for (int var7 = 0; var7 < var6.length; ++var7) {
                if (var6[var7].getName().equals(var5)) {
                    SnmpObjectType var8 = (SnmpObjectType) var6[var7].getType();
                    if (var8.getAccess().canWrite()) {
                        var3.add(var6[var7]);
                        break;
                    }
                }
            }
        }

        return var3;
    }

    /**
     * 校验返回是否异常
     *
     * @param event
     * @throws SenaSnmpRunTimeException
     */
    public static void checkSnmpError(ResponseEvent event) throws SenaSnmpRunTimeException {
        if (event.getError() != null) {
            log.error("返回数据校验失败:{}", event.getError().getMessage());
            throw new SenaSnmpRunTimeException(event.getError().getMessage());
        } else {
            PDU pdu = event.getResponse();
            if (pdu == null) {
                //请求超时
                log.error("返回数据校验失败:{}", "请求超时");
                throw new SenaSnmpRunTimeException(SnmpResultCodeEnum.SNMP_TIME_OUT);
            } else if (pdu.getErrorStatus() != 0) {
                if (pdu.getErrorStatus() == 2) {
                    throw new SenaSnmpRunTimeException(SnmpResultCodeEnum.SNMP_NODE_NOT_FOUND);
                } else {
                    throw new SenaSnmpRunTimeException(pdu.getErrorStatusText());
                }
            } else {
                VariableBinding variableBinding = pdu.get(0);
                if (variableBinding == null) {
                    log.error("返回数据校验失败:{}", "请求超时");
                    throw new SenaSnmpRunTimeException(SnmpResultCodeEnum.SNMP_TIME_OUT);
                } else {
                    List list = pdu.getVariableBindings();
                    if (list.size() <= 0) {
                        throw new SenaSnmpRunTimeException(SnmpResultCodeEnum.SNMP_TIME_OUT);
                    }
                }
            }
        }
    }

    /**
     * 格式化输出IP地址
     *
     * @param ipString
     * @return
     */
    public static String formatDisplayIP(String ipString) {
        if (StringUtils.isNotBlank(ipString) && !"null".equalsIgnoreCase(ipString)) {
            try {
                byte[] bytes = ipString.getBytes(StandardCharsets.ISO_8859_1);
                boolean flag = false;
                for (int i = 0; i < bytes.length; i++) {
                    char c = (char) bytes[i];
                    if ((Character.isISOControl(c) || (bytes[i] & 255) >= 128) && !Character.isWhitespace(c)) {
                        flag = true;
                        break;
                    }
                }

                return !flag ? ipString : InetAddress.getByAddress(bytes).getHostAddress();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("格式化IP地址失败");
                return ipString;
            }
        } else {
            return "";
        }
    }

    /**
     * 格式化mac地址
     *
     * @param
     * @return
     */
//    public static String formatDispayMacAddress(String macAddr) {
//        String addr = "";
//        if (macAddr != null && !macAddr.equals("") && !macAddr.equalsIgnoreCase("null")) {
//            try {
//                OctetString octetString = new OctetString(macAddr.getBytes(StandardCharsets.UTF_8));
//                addr = octetString.toHexString();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        return addr;
//    }
    public static String formatDisplayMacAddress(String mac) {
        if (StringUtils.isNotBlank(mac) && !"null".equalsIgnoreCase(mac)) {
            try {
                byte[] macBytes = mac.getBytes("ISO-8859-1");
                boolean flag = false;
                for (int i = 0; i < macBytes.length; i++) {
                    char c = (char) macBytes[i];
                    if ((Character.isISOControl(c) || (macBytes[i] & 255) >= 128) && !Character.isWhitespace(c)) {
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    return mac;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                OctetString octetString = new OctetString(mac.getBytes("ISO-8859-1"));
                return octetString.toHexString();
            } catch (Exception e) {
                log.error("格式化MAC地址失败");
                e.printStackTrace();
                return "";
            }
        } else {
            return "";
        }
    }

    /**
     * 格式化文字符
     * @param str
     * @return
     */
    public static String formatCNString(String str) {
        String reStr = "";
        if (str != null && !str.equals("") && !str.equalsIgnoreCase("null")) {
            try {
                reStr = new String(str.getBytes("iso8859_1"), StandardCharsets.UTF_8);
                return reStr;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return reStr;
    }

    public static boolean canPing(String ip) {
        try {
            InetAddress var1 = InetAddress.getByName(ip);
            return var1.isReachable(30);
        } catch (Exception e) {
            System.out.println("设备 " + ip + ":无法到达----");
            log.error("isReachable ping host:" + ip + ",erro:" + e.getMessage());
            return false;
        }
    }

    /**
     * 关闭流的通用方法
     *
     * @param snmp
     */
    public static void closeSnmp(Snmp snmp) {
        try {
            if (snmp != null) {
                snmp.close();
            }
        } catch (Exception e) {
            log.error("关闭snmp失败", e);
        }
    }


    public static PDU createPdu(int version) {
        PDU pdu = null;
        if (version == SnmpConstants.version3) {
            pdu = new ScopedPDU();
        } else {
            pdu = new PDUv1();
        }
        return pdu;
    }


    public static  MibValueSymbol getMibSymbolByOid(String oid)  {
        if (oid.startsWith(".")) {
            oid = oid.replaceFirst(".", "");
        }
        ObjectIdentifierValue iso = MibLoaderBuilder.getMibloader().getRootOid();
        ObjectIdentifierValue match = iso.find(oid);
        if (match == null) {
            log.error("oid:" + oid + "未找到该oid的节点");
            return null;
        } else {
            return match.getSymbol();
        }
    }
}
